{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": true
   },
   "outputs": [],
   "source": [
    "import tensorflow as tf\n",
    "from tensorflow.examples.tutorials.mnist import input_data\n",
    "\n",
    "# Read data\n",
    "mnist = input_data.read_data_sets(\"MNIST_data/\", one_hot=True)\n",
    "\n",
    "# Python optimisation variables\n",
    "learning_rate = 0.5\n",
    "epochs = 10\n",
    "batch_size = 100\n",
    "\n",
    "# input x - for 28 x 28 pixels = 784\n",
    "x = tf.placeholder(tf.float32, [None, 784])\n",
    "y = tf.placeholder(tf.float32, [None, 10])\n",
    "\n",
    "# 隐层1\n",
    "W1 = tf.Variable(tf.random_normal([784, 300], stddev=0.03), name='W1')\n",
    "b1 = tf.Variable(tf.random_normal([300]), name='b1')\n",
    "# 隐层2\n",
    "W2 = tf.Variable(tf.random_normal([300, 10], stddev=0.03), name='W2')\n",
    "b2 = tf.Variable(tf.random_normal([10]), name='b2')\n",
    "\n",
    "# 隐层1的输出\n",
    "hidden_out = tf.add(tf.matmul(x, W1), b1)\n",
    "hidden_out = tf.nn.relu(hidden_out)\n",
    "\n",
    "# 隐层2的输出作为softmax输入进行分类\n",
    "y_ = tf.nn.softmax(tf.add(tf.matmul(hidden_out, W2), b2))\n",
    "\n",
    "#tf.clip_by_value(A, min, max)：输入一个张量A，把A中的每一个元素的值都压缩在min和max之间。小于min的让它等于min，大于max的元素的值等于max。\n",
    "y_clipped = tf.clip_by_value(y_, 1e-10, 0.9999999)\n",
    "\n",
    "#交叉熵损失函数\n",
    "cross_entropy = -tf.reduce_mean(tf.reduce_sum(y * tf.log(y_clipped)\n",
    "                                              + (1 - y) * tf.log(1 - y_clipped), axis=1))\n",
    "\n",
    "\n",
    "# 最速梯度下降\n",
    "optimiser = tf.train.GradientDescentOptimizer(learning_rate=learning_rate).minimize(cross_entropy)\n",
    "\n",
    "init_op = tf.global_variables_initializer()\n",
    "\n",
    "correct_prediction = tf.equal(tf.argmax(y, 1), tf.argmax(y_, 1))\n",
    "accuracy = tf.reduce_mean(tf.cast(correct_prediction, tf.float32))\n",
    "\n",
    "with tf.Session() as sess:\n",
    "    sess.run(init_op)\n",
    "    total_batch = int(len(mnist.train.labels) / batch_size)\n",
    "    for epoch in range(epochs):\n",
    "        avg_cost = 0\n",
    "        for i in range(total_batch):\n",
    "            batch_x, batch_y = mnist.train.next_batch(batch_size=batch_size)\n",
    "            _, c = sess.run([optimiser, cross_entropy],\n",
    "                            feed_dict={x: batch_x, y: batch_y})\n",
    "            avg_cost += c / total_batch\n",
    "        print(\"Epoch:\", (epoch + 1), \"cost =\", \"{:.3f}\".format(avg_cost))\n",
    "\n",
    "    print(sess.run(accuracy, feed_dict={x: mnist.test.images, y: mnist.test.labels}))"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 2",
   "language": "python",
   "name": "python2"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 2
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython2",
   "version": "2.7.6"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 0
}
